package com.p7.architect.store.product.client.rpc;

import com.p7.architect.store.product.client.rpc.sku.SkuRequest;
import com.p7.architect.store.product.client.rpc.sku.SkuResponse;
import com.p7.architect.store.product.client.rpc.sku.SkuServiceGrpc;
import com.p7.architect.store.product.client.rpc.sku.SkuVo;
import com.p7.architect.store.product.client.vo.SkuRpcVo;
import io.grpc.stub.StreamObserver;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;

@RequiredArgsConstructor
@Component
public class SkuServiceGrpcImpl extends SkuServiceGrpc.SkuServiceImplBase {

    private final SkuRpc skuRpc;

    @Override
    public void getSkuListBySkuIdList(SkuRequest request, StreamObserver<SkuResponse> responseObserver) {
        SkuResponse.Builder builder = SkuResponse.newBuilder();
        builder.setCode(0).setMsg("success").setSuccess(true);

        SkuResponse.Data.Builder dataBuilder = SkuResponse.Data.newBuilder();
        List<SkuRpcVo> skuRpcVoList = skuRpc.getSkuListBySkuIdList(request.getSkuIdListList());
        if (CollectionUtils.isEmpty(skuRpcVoList)) {
            builder.setData(dataBuilder);
            return;
        }

        for (SkuRpcVo rpcVo : skuRpcVoList) {
            SkuVo.Builder skuVoBuilder = SkuVo.newBuilder();
            skuVoBuilder.setSkuId(rpcVo.getSkuId());
            skuVoBuilder.setSpuId(rpcVo.getSpuId());
            skuVoBuilder.setSkuName(rpcVo.getSkuName());
            skuVoBuilder.setSkuTitle(rpcVo.getSkuTitle());
            skuVoBuilder.setSkuDefaultImg(rpcVo.getSkuDefaultImg());
            skuVoBuilder.setSkuSubtitle(rpcVo.getSkuSubtitle());
            skuVoBuilder.setPrice(rpcVo.getPrice());
            dataBuilder.addSkuVo(skuVoBuilder);
        }
        builder.setData(dataBuilder);

        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }
}
